package com.asiainfo.kbisheet.util;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.asiainfo.kbisheet.vo.DataSourceVO;

/**
 * C3P0的数据源池
 * 
 * @author kyunra
 * 
 */
public class DspDBCP {
	protected static final Log log = LogFactory.getLog(DspDBCP.class);

	private static DspDBCP instance;

	public static DspDBCP getInstance() {
		if (instance == null) {
			instance = new DspDBCP();
		}
		return instance;
	}

	private Map<String, BasicDataSource> dsMap = new Hashtable<String, BasicDataSource>();

	private DspDBCP() {
	}

	public Connection getConnection(DataSourceVO dataSourceVO) throws SQLException, PropertyVetoException {
		BasicDataSource ds = getDataSource(dataSourceVO);
		log.info(dataSourceVO.getUrl() + " : NumActive = " + ds.getNumActive() + "; NumIdle = " + ds.getNumIdle());
		return ds.getConnection();
	}

	private synchronized BasicDataSource getDataSource(DataSourceVO dataSourceVO) throws PropertyVetoException {
		BasicDataSource ds;
		if (dsMap.containsKey(dataSourceVO.getKey())) {
			ds = dsMap.get(dataSourceVO.getKey());
		}
		else {
			ds = new BasicDataSource();
			ds.setDriverClassName(dataSourceVO.getDriverClassName());
			ds.setUrl(dataSourceVO.getUrl());
			ds.setUsername(dataSourceVO.getUser());
			ds.setPassword(dataSourceVO.getPassword());
			ds.setMaxIdle(0);
			ds.setMinIdle(0);
			ds.setMaxWait(1000);
			ds.setMaxActive(200);
			dsMap.put(dataSourceVO.getKey(), ds);
		}
		return ds;
	}
}
